package com.loop.unclelend.utils.dialog

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.graphics.Typeface
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.loop.unclelend.MyApplication
import com.loop.unclelend.R
import com.loop.unclelend.databinding.UncleDialogStepBirthdayBinding
import com.loop.unclelend.pro.ProDialog
import com.loop.unclelend.utils.DensityUtils
import com.loop.unclelend.utils.ToastManager
import com.loop.unclelend.utils.adapter.UncleOnItemChildClickListener
import com.loop.unclelend.utils.adapter.UncleRecyclerViewAdapter
import com.loop.unclelend.utils.adapter.UncleViewHolderHelper
import com.loop.unclelend.utils.decoration.GridSpacingItemDecoration
import com.loop.unclelend.utils.event.UncleEventHelper
import com.loop.unclelend.utils.event.UncleEventType
import com.loop.unclelend.utils.helper.UncleDateHelper
import org.json.JSONObject
import java.text.SimpleDateFormat
import java.util.Calendar

/**
 * UncleLend
 * @Author wwdeng
 * @CreateTime: 2024/9/12 13:54
 * @Annotation：流程选择出生日期
 */
class Dialog_Step_Birthday: ProDialog {
    private lateinit var binding: UncleDialogStepBirthdayBinding
    private var mCallback: IDialogCallback? = null
    //事件备注
    private var eventRemark = ""
    /* 日期 */
    private var mDayAdapter: DayAdapter? = null

    //年
    private var showYear = UncleDateHelper.getCurtYear()
    //月
    private var showMonth = UncleDateHelper.getCurtMonth()
    //日
    private var showDay = UncleDateHelper.getCurtDay()

    constructor(context: Context?) : super(context) {}
    constructor(context: Context?, callback: IDialogCallback?) : super(context) {
        mCallback = callback
    }

    constructor(context: Context?, remark: String,callback: IDialogCallback?) : super(context) {
        mCallback = callback
        eventRemark = remark
    }

    /**
     * 设置点击回调
     */
    fun setOnClick(callback: IDialogCallback){
        this.mCallback = callback
    }

    override fun initWindow() {
        val params = window!!.attributes
        params.width = MyApplication.app.getPhoneWidth()
        params.height = WindowManager.LayoutParams.WRAP_CONTENT
        window!!.attributes = params
        window!!.setWindowAnimations(R.style.dialog_slide_anim) //修改动画样式
        window!!.setGravity(Gravity.BOTTOM)
    }

    override fun getRootView(): View {
        binding = UncleDialogStepBirthdayBinding.inflate(LayoutInflater.from(context))
        return binding.root
    }

    override fun initView() {
        initRecyclerViewWeek()
        initRecyclerViewDay()
    }

    override fun initListener() {
        setOnClickListener(binding.btnDone)
        //上一年
        binding.imgYearLast.setOnClickListener {
            showYear = UncleDateHelper.getLastYear(showYear).get(Calendar.YEAR)
            showYear()
            showDay()
        }
        //下一年
        binding.imgYearNext.setOnClickListener {
            showYear = UncleDateHelper.getNextYear(showYear).get(Calendar.YEAR)
            showYear()
            showDay()
        }

        //上一月
        binding.imgMonthLast.setOnClickListener {
            val calendar = UncleDateHelper.getLastMonth(showYear,showMonth)
            showYear = calendar.get(Calendar.YEAR)
            showMonth = calendar.get(Calendar.MONTH)+1
            showYear()
            showMonth()
            showDay()
        }

        //下一月
        binding.imgMonthNext.setOnClickListener {
            val calendar = UncleDateHelper.getNextMonth(showYear,showMonth)
            showYear = calendar.get(Calendar.YEAR)
            showMonth = calendar.get(Calendar.MONTH)+1
            showYear()
            showMonth()
            showDay()
        }
    }

    override fun initData() {
        showYear()
        showMonth()
        showDay()
    }

    @SuppressLint("SimpleDateFormat")
    override fun onViewClick(v: View?) {
        when (v!!.id) {
            R.id.btn_done -> {//提交
                val selectDay = getSelectDay()
                if (selectDay == 0){
                    ToastManager.showShortText(context,context.getString(R.string.tips_select_birth_error))
                    return
                }
                dismiss()
                var formatDay = "$selectDay"
                if (selectDay < 10){
                    formatDay = "0$selectDay"
                }

                val calendar = Calendar.getInstance()
                calendar.set(Calendar.YEAR, showYear)
                calendar.set(Calendar.MONTH, showMonth-1)
                calendar.set(Calendar.DAY_OF_MONTH, selectDay)
                val obj = JSONObject()
                obj.put("showDate","$formatDay-${UncleDateHelper.getMonthList()[showMonth - 1].optString("month")}-$showYear")
                obj.put("subDate",SimpleDateFormat("yyyy-MM-dd").format(calendar.timeInMillis))
                if (mCallback != null){
                    mCallback!!.completed(obj)
                }
            }
        }
    }

    interface IDialogCallback {
        fun completed(selectDate: JSONObject)
    }

    /**
     * 设置月份
     */
    private fun initRecyclerViewWeek(){
        binding.rvWeek.setHasFixedSize(true)
        binding.rvWeek.isNestedScrollingEnabled = false
        binding.rvWeek.isFocusableInTouchMode = false //不需要焦点
        val decoration = DensityUtils.dp2px(12f)
        binding.rvWeek.addItemDecoration(GridSpacingItemDecoration(7,decoration,true))
        val layoutManager = GridLayoutManager(context,7)
        binding.rvWeek.layoutManager = layoutManager
        val weekAdapter = WeekAdapter(binding.rvWeek)
        binding.rvWeek.adapter = weekAdapter
        binding.rvWeek.itemAnimator = DefaultItemAnimator()
        weekAdapter.data = UncleDateHelper.getWeekList()
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun initRecyclerViewDay() {
        binding.rvDay.setHasFixedSize(true)
        binding.rvDay.isNestedScrollingEnabled = false
        binding.rvDay.isFocusableInTouchMode = false //不需要焦点
        val decoration = DensityUtils.dp2px(12f)
        binding.rvDay.addItemDecoration(GridSpacingItemDecoration(7,decoration,true))
        val layoutManager = GridLayoutManager(context,7)
        binding.rvDay.layoutManager = layoutManager
        mDayAdapter = DayAdapter(binding.rvDay)
        binding.rvDay.adapter = mDayAdapter
        binding.rvDay.itemAnimator = DefaultItemAnimator()
        mDayAdapter!!.setOnItemChildClickListener(UncleOnItemChildClickListener { _, _, position ->
            val item = mDayAdapter!!.getItem(position)
            if (item.optBoolean("isSelect") || item.optInt("day") == 0){
                return@UncleOnItemChildClickListener
            }
            for (i in 0..<mDayAdapter!!.itemCount){
                val obj = mDayAdapter!!.getItem(i)
                obj.put("isSelect",false)
                if (i == position){
                    obj.put("isSelect",true)
                }
            }
            mDayAdapter!!.notifyDataSetChanged()
        })
    }

    /**
     * 设置年份
     */
    private fun showYear(){
        binding.txtYear.text = "$showYear"
    }

    /**
     * 设置月份
     */
    private fun showMonth(){
        val month = UncleDateHelper.getMonthList()[showMonth - 1]
        binding.txtMonth.text = month.optString("month")
    }

    /**
     * 设置日期
     */
    private fun showDay(){
        val dayList = arrayListOf<JSONObject>()
        //指定年月的1号是星期几
        val week = UncleDateHelper.getDayOfWeek(showYear,showMonth,1)
        for (i in 0..<week){
            val item  = JSONObject()
            item.put("year",0)
            item.put("month",0)
            item.put("day",0)
            dayList.add(item)
        }
        dayList.addAll(UncleDateHelper.getDayList(showYear,showMonth))
        for (i in 0..<dayList.size){
            val day = dayList[i]
            day.put("isSelect",false)
            if (showYear == UncleDateHelper.getCurtYear() && showMonth == UncleDateHelper.getCurtMonth() && day.optInt("day") == showDay){
                day.put("isSelect",true)
            }
        }
        mDayAdapter!!.data = dayList
    }

    /**
     * 获取选中的日期
     */
    private fun getSelectDay(): Int{
        var day = 0
        for (i in 0..<mDayAdapter!!.itemCount){
            val item = mDayAdapter!!.getItem(i)
            if (item.optBoolean("isSelect")){
                day = item.optInt("day")
                break
            }
        }
        return day
    }

    /**
     * 周
     */
    internal inner class WeekAdapter(recyclerView: RecyclerView?) : UncleRecyclerViewAdapter<String>(recyclerView, R.layout.uncle_item_step_birthday_week) {
        override fun fillData(helper: UncleViewHolderHelper, position: Int, model: String) {
            val txtWeek = helper.getTextView(R.id.txt_week)
            helper.setText(R.id.txt_week,model)
        }
    }

    /**
     * 日期
     */
    internal inner class DayAdapter(recyclerView: RecyclerView?) : UncleRecyclerViewAdapter<JSONObject>(recyclerView, R.layout.uncle_item_step_birthday_day) {
        override fun setItemChildListener(helper: UncleViewHolderHelper, viewType: Int) {
            helper.setItemChildClickListener(R.id.txt_day) //点击Item
        }

        override fun fillData(helper: UncleViewHolderHelper, position: Int, model: JSONObject) {
            val textDay = helper.getTextView(R.id.txt_day)
            val showDay = model.optInt("day")
            if (showDay == 0){
                textDay.text = ""
            } else {
                textDay.text = "$showDay"
            }

            if (model.optBoolean("isSelect")){
                textDay.setTypeface(Typeface.DEFAULT,Typeface.BOLD)
                textDay.setTextColor(Color.parseColor("#FFFFFFFF"))
                textDay.setBackgroundResource(R.drawable.circle_fill_ff7000ff)
            } else {
                textDay.setTypeface(Typeface.DEFAULT,Typeface.NORMAL)
                textDay.setTextColor(Color.parseColor("#FF0F2552"))
                textDay.setBackgroundColor(Color.parseColor("#00000000"))
            }
        }
    }

    override fun onStart() {
        super.onStart()
        UncleEventHelper.addUncleRequestEventAction(UncleEventType.DIALOG.UNCLE_DIALOG_BIRTHDAY_SHOW,eventRemark)
    }

    override fun dismiss() {
        super.dismiss()
        UncleEventHelper.addUncleRequestEventAction(UncleEventType.DIALOG.UNCLE_DIALOG_BIRTHDAY_DISMISS,eventRemark)
    }
}